<template>
  <div class="header">
    <div class="system">
      <img src="@/assets/img/logo.png" style="object-fit: contain" />
      <div class="split-line"></div>
      <div class="name" v-text="state.systemName"></div>
    </div>
    <div class="city-time-header">
      <span>{{ state.cityName }}</span>
    </div>
    <BoardMenu></BoardMenu>
    <el-popover
      placement="bottom"
      popper-class="login-name"
      width="auto"
      trigger="hover"
    >
      <template #reference>
        <div class="person">
          <el-image :src="state.userImg" fit="contain">
            <template #error>
              <div class="image-slot">
                <em class="tbdfont tbd-touxiang"></em>
              </div>
            </template>
          </el-image>
          <div class="userName" v-text="state.userName"></div>
          <div class="set"><em class="tbdfont tbd-xiajiantou"></em></div>
        </div>
      </template>
      <div class="person-list">
        <div class="person-list-item" @click="showLogout">登出</div>
        <div class="person-list-item" @click="showAbout">关于</div>
        <div class="person-list-item" @click="resetPassWord">重置密码</div>
      </div>
    </el-popover>
  </div>

  <div class="custom-el-plus">
    <el-dialog
      v-model="state.isShowResetConfirm"
      width="27%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      align-center
      title="重置密码"
      @close="resetForm"
    >
      <div class="reset-body">
        <el-form
          ref="passwordFormRef"
          :model="formParam"
          :rules="rules"
          label-position="right"
        >
          <el-form-item label="原密码" prop="oldPwd" label-width="100px">
            <el-input
              v-model="formParam.oldPwd"
              type="password"
              show-password
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPwd" label-width="100px">
            <el-input
              v-model="formParam.newPwd"
              type="password"
              show-password
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item
            label="确认新密码"
            prop="newPwdConfirm"
            label-width="100px"
          >
            <el-input
              v-model="formParam.newPwdConfirm"
              type="password"
              show-password
              autocomplete="off"
            />
          </el-form-item>
          <div
            class="error-input"
            :style="[state.errorInput ? '' : 'visibility: hidden;']"
            v-text="state.errorInput"
          ></div>
        </el-form>
      </div>
      <template #footer>
        <div class="btn-box">
          <el-button plain @click="state.isShowResetConfirm = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            color="#165DFF"
            @click="saveReset(passwordFormRef)"
            >提交</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  reactive,
  getCurrentInstance,
  onUnmounted,
  onMounted,
  h,
} from "vue";
import { useRouter } from "vue-router";
import Timer from "@/utils/timerClass.js";
import CryptoJS from "crypto-js";
import showAboutFun from "@/hooks/showAboutMan.js";
import BoardMenu from "./boardMenu.vue";
import useUserMessage from "@/store/userMessage.js";
import { solarPowerSystem } from "@/common/projectAlias";
import { ElMessageBox } from "element-plus";
const { showAbout } = showAboutFun();
const userMessage = useUserMessage();
const router = useRouter();
const { proxy } = getCurrentInstance();
const state = reactive({
  systemName: systemConfig.systemName,
  userName: computed(() => userMessage.userName),
  userImg: computed(() => userMessage.picUrl),
  cityName: "张家口",
  isShowResetConfirm: false,
  passwordFormRef: null,
  errorInput: null, //保存错误的提示
});
const passwordFormRef = ref(null);
const formParam = reactive({
  loginName: computed(() => userMessage.userName),
  oldPwd: "",
  newPwd: "",
  newPwdConfirm: "",
});
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('确认新密码不能为空'))
  } else if (value !== formParam.newPwd) {
    callback(new Error("两次新密码输入不一致，请重新确认"))
  } else {
    callback()
  }
}
const rules = reactive({
  oldPwd: [{required: true, message: '原密码不能为空！', trigger: 'blur'}],
  newPwd: [{required: true, message: '新密码不能为空！', trigger: 'blur'}],
  newPwdConfirm: [
    {required: true, message: '确认新密码不能为空!', trigger: 'blur'},
    {validator: validatePass2, trigger: 'blur'}
  ],
})
const saveReset = (ref) => {
  ref.validate((valid) => {
    if (!valid) return false;

    //aes cbc  加密
    let key = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_AES_CBC_KEY)
    let iv = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_AES_CBC_IV)
    let oldPassword = CryptoJS.AES.encrypt(formParam.oldPwd, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });
    let newPassword = CryptoJS.AES.encrypt(formParam.newPwd, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });
    let name = CryptoJS.AES.encrypt(formParam.loginName, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });

    proxy.$http.postLoginWithBody('login/updatePwd', {
      loginName: name.toString(),
      oldPwd: oldPassword.toString(),
      newPwd: newPassword.toString(),
    }).then(() => {
      proxy.$tipMessage('重置成功！','success')
      state.isShowResetConfirm = false;

      //记住密码中，若有，修改记录
      let base = window.btoa(formParam.newPwd)
      let cipher = localStorage.storeCipher ? JSON.parse(localStorage.storeCipher) : {};
      if (cipher.hasOwnProperty(formParam.loginName)){
        cipher[formParam.loginName] = base;
        localStorage.storeCipher = JSON.stringify(cipher);
      }
    }).catch((error) => {
      state.errorInput = error.data.error_msg;
      console.log('密码重置失败', error)
    })
  })
}
const resetForm = () => {
  formParam.oldPwd = "";
  formParam.newPwd = "";
  formParam.newPwdConfirm = "";
}
const loginOut = () => {
  return proxy.$http.getLoginWithUrl("login/logout", {
    projectAlias: solarPowerSystem,
  });
};

const showLogout = () => {
  ElMessageBox({
    title: "",
    cancelButtonClass: "messagebox-cancel-btn",
    confirmButtonClass: "messagebox-confirm-btn",
    customStyle: {
      backgroundColor: "#0D172F",
      borderRadius: "8px",
    },
    message: h("p", null, [
      h("div", { style: "color: #A5ADBA; margin: 2.781vh 0 3.708vh 0.624vw" }, "确认退出当前系统吗?"),
    ]),
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        loginOut()
          .then(() => {
            sessionStorage.removeItem("aiUserMessage");
            //删除菜单
            sessionStorage.removeItem("aiBoardMenu");
            router.push("/login"); //跳转到登录
            done();
          })
          .catch((error) => {
            console.log(error); //登出失败
            done()
          });
      } else {
        done();
      }
    },
  }).then((action) => {
  });
};
const resetPassWord = () => {
  state.isShowResetConfirm = true;
};
onMounted(() => {

});
onUnmounted(() => {

});
</script>

<style scoped lang="scss">
.header {
  // z-index: 10;
  height: pxTvh(56);
  @include elasticFN(flex-start, center);
  box-shadow: inset 0px -1px 0px 0px rgba(0, 0, 0, 0.1);
  padding: 0 pxTvw(32) 0 pxTvw(35);
  background: #111d3e;
  width: 100%;
  border: 1px solid rgba(126, 169, 255, 0.2);
  box-sizing: border-box;
  & > .system {
    @include elasticFN(space-between, center);
    height: pxTvh(28);
    & > img {
      // @include imgSize(28.43);
      width: pxTvw(24);
      height: pxTv2(24);
    }
    & > .split-line {
      margin: 0 pxTvw(8);
      background-color: #54667a;
      height: pxTvh(21);
      width: pxTvw(1);
    }
    & > .name {
      @include computed_font(20);
      @include textHeight(30);
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 500;
      color: #ffffff;
      // margin-left: pxTvw(16);
    }
  }
  & > .city-time-header {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    @include computed_font(14);
    color: #ffffff;
    & > span:nth-child(1) {
      margin-left: pxTvw(29);
      @include computed_font(16);
    }
    & > span:nth-child(2) {
      margin-left: pxTvw(24);
      color: #d3dfff;
    }
    & > span:nth-child(3) {
      margin-left: pxTvw(5);
      color: #d3dfff;
    }
    & > span:nth-child(4) {
      margin-left: pxTvw(5);
      color: #d3dfff;
    }
  }
  & > .person {
    @include elasticFN(center, center);
    margin-left: auto;
    height: pxTvh(34);
    & > .el-image {
      background-color: rgba(68, 90, 143, 1);
      border-radius: 50%;
      @include imgSize(30);
      :deep(.el-image__inner) {
        width: 100%;
        height: 100%;
      }
      .image-slot {
        color: #bed3e6;
        text-align: center;
        line-height: pxTvh(34);
        em {
          @include computed_font(20);
        }
      }
    }
    .userName {
      margin-right: pxTvw(8);
      margin-left: pxTvw(8);
      @include computed_font(14);
      height: 100%;
      @include elasticFN(center, center);
      font-family: Source Han Sans CN-Bold, Source Han Sans CN, sans-serif;
      color: #bed3e6;
    }
    .set {
      font-weight: 400;
      color: #777777;
      em {
        @include computed_font(12);
        @include cursorFN();
      }
    }
  }
}
.login-name {
  .person-list {
    &-item {
      transition: all 200ms;
      padding: pxTvh(5) pxTvw(16);
      text-align: center;
      &:hover {
        //font-weight: bold;
        cursor: pointer;
      }
    }
  }
}
.reset-body {
  .el-form {
    display: block;
    margin: pxTvh(30) pxTvw(20) pxTvh(10) pxTvw(20);
    & > .el-form-item:nth-child(2) {
      margin-top: pxTvh(24);
    }
    & > .el-form-item:nth-child(3) {
      margin-top: pxTvw(24);
    }
  }
  :deep(input:-webkit-autofill) {
    -webkit-box-shadow:0 0 0 1000px #19284D inset !important;
    -webkit-text-fill-color: #cfdbfc;
  }
}
.btn-box {
  & > .el-button:nth-child(2) {
    margin-right: pxTvw(20);
  }
}

</style>
<style lang="scss">
//影响所有下拉框
.el-popper {
  --el-bg-color-overlay: rgb(22, 49, 86);
  --el-border-color-light: rgb(22, 49, 86);
  color: #e8f3ff;
  @include computed_font(14);
}
.login-name {
  --el-text-color-regular: #e8f3ff;
  --el-bg-color-overlay: #102644;
  .person-list-item {
    &:hover {
      color: #6aa1ff;
    }
  }
}

</style>